package com.library.web.sys_user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.library.annotation.Auth;
import com.library.jwt.JwtUtils;
import com.library.utils.ResultUtils;
import com.library.utils.ResultVo;
import com.library.web.sys_reader.pojo.SysReader;
import com.library.web.sys_reader.service.SysReaderService;
import com.library.web.sys_role.pojo.SysRole;
import com.library.web.sys_role.service.SysRoleService;
import com.library.web.sys_user.pojo.PageParm;
import com.library.web.sys_user.pojo.SysUser;
import com.library.web.sys_user.pojo.UpdatePasswordParm;
import com.library.web.sys_user.service.SysUserService;
import com.library.web.sys_user_role.pojo.UserRole;
import com.library.web.sys_user_role.service.UserRoleService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private SysReaderService sysReaderService;
    @Autowired
    private JwtUtils jwtUtils;

    //新增用户
    @PostMapping
    @Auth
    public ResultVo addUser(@RequestBody SysUser user) {
        //判断账户知否被占用
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        //需要用lambda的方式使用mapper ::(双冒号)java8特性
        query.lambda().eq(SysUser::getUsername, user.getUsername());
        SysUser oneUser = sysUserService.getOne(query);
        if (oneUser != null) {
            return ResultUtils.error("账户被占用！");
        }
        //密码MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //设置是不是管理员
        user.setIsAdmin("0");
        user.setCreateTime(new Date());
        sysUserService.addUser(user);
        return ResultUtils.success("新增用户成功!");
    }

    //编辑用户
    @PutMapping
    @Auth
    public ResultVo editUser(@RequestBody SysUser user) {
        //判断账户知否被占用
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        //需要用lambda的方式使用mapper ::(双冒号)java8特性
        query.lambda().eq(SysUser::getUsername, user.getUsername());
        SysUser oneUser = sysUserService.getOne(query);
        if (oneUser != null && !oneUser.getUserId().equals(user.getUserId())) {
            return ResultUtils.error("账户被占用！");
        }
        //密码MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setUpdateTime(new Date());
        //更新
        sysUserService.editUser(user);
        return ResultUtils.success("编辑用户成功!");
    }

    //删除用户
    @DeleteMapping("/{userId}")
    @Auth
    public ResultVo deleteUser(@PathVariable("userId") Long userId) {
        //根据用户Id查询出用户角色表，删除用户角色也会删除！
        UserRole userRole = userRoleService.selectUserRoleIdByUserId(userId);
        boolean userRoleId = userRoleService.removeById(userRole.getUserRoleId());
        boolean remove = sysUserService.removeById(userId);
        if (remove && userRoleId) {
            return ResultUtils.success("删除用户成功!");
        }
        return ResultUtils.error("删除用户失败!");
    }

    //列表分页查询
    @GetMapping("/list")
    @Auth
    public ResultVo getList(PageParm parm) {
        IPage<SysUser> list = sysUserService.list(parm);
        //密码处理前端的JSON不会有密码这个或者可以自定义密码
        list.getRecords().stream().forEach(item -> {
            item.setPassword("");
        });
        return ResultUtils.success("查询成功", list);
    }

    //根据用户id查询角色id
    @GetMapping("/getRoleId")
    @Auth
    public ResultVo getRoleId(String userId) {
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.lambda().eq(UserRole::getUserId, userId);
        UserRole one = userRoleService.getOne(query);
        return ResultUtils.success("查询成功", one);
    }

    //查询角色列表
    @GetMapping("/getRoleList")
    @Auth
    public ResultVo getRoleList() {
        List<SysRole> list = sysRoleService.list();
        return ResultUtils.success("查询成功", list);
    }

    //修改密码
    @Auth
    @PostMapping("/updatePassword")
    public ResultVo updatePassword(@RequestBody UpdatePasswordParm parm, HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claims = jwtUtils.getClaimsFromToken(token);
        Object userType = claims.get("userType");
        String old = DigestUtils.md5DigestAsHex(parm.getOldPassword().getBytes());
        if (userType.equals("0")) { //读者
            SysReader reader = sysReaderService.getById(parm.getUserId());
            if (!reader.getPassword().equals(old)) {
                return ResultUtils.error("原密码不正确!");
            }
            SysReader sysReader = new SysReader();
            sysReader.setReaderId(parm.getUserId());
            sysReader.setPassword(DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()));
            boolean b = sysReaderService.updateById(sysReader);
            if (b) {
                return ResultUtils.success("密码修改成功!");
            }
        } else {
            SysUser user = sysUserService.getById(parm.getUserId());
            if (!user.getPassword().equals(old)) {
                return ResultUtils.error("原密码不正确!");
            }
            SysUser sysUser = new SysUser();
            sysUser.setUserId(parm.getUserId());
            sysUser.setPassword(DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()));
            boolean b = sysUserService.updateById(sysUser);
            if (b) {
                return ResultUtils.success("密码修改成功!");
            }
        }
        return ResultUtils.error("密码修改失败!");
    }

    //重置密码
    @PutMapping("/resetPassword")
    public ResultVo resetPassword(@RequestBody SysUser sysUser) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().eq(SysUser::getUsername, sysUser.getUsername()).eq(SysUser::getPhone, sysUser.getPhone()).eq(SysUser::getEmail, sysUser.getEmail());
        SysUser one = sysUserService.getOne(query);
        if (one != null) {
            String passWord = "LibraryAdminUser";
            one.setPassword(DigestUtils.md5DigestAsHex(passWord.getBytes()));
            boolean b = sysUserService.updateById(one);
            if (b) {
                return ResultUtils.success("重置密码成功,密码是LibraryAdminUser请及时修改密码！！！");
            }
            return ResultUtils.error("重置密码失败!");
        }
        return ResultUtils.error("重置密码失败!");
    }
}
